#!/usr/bin/python
# -*- coding: utf-8 -*-

import Ice
import sys, os, array, time

try:
    HOME = os.environ['RENDERING_CLUSTER']
except KeyError:
    print 'RENDERING_CLUSTER environment variable is not currently defined.'
    sys.exit(0)

SLICE = os.path.join(HOME, 'slice')
FILE = os.path.join(SLICE, 'Cluster.ice')
Ice.loadSlice('--all -I/usr/share/slice', ['-I' + SLICE, FILE])

MODEL_DIR = os.path.join(HOME, 'src', 'model')
PROJECT_NAME = 'project.blend'
PROJECT_FILE = os.path.join(MODEL_DIR, PROJECT_NAME)

OUTPUT_BLENDER_DIR = '../output'
OUTPUT_BLENDER_FILE = os.path.join(OUTPUT_BLENDER_DIR, 'frame_')

OUTPUT_DIR = os.path.join(HOME, 'src','output')


import Cluster

class RenderNodeI (Cluster.RenderNode):

    def __init__ (self):
        
        pass

    def setProject (self, project, curr = None):
        
        array.array('B', project).tofile(open(PROJECT_FILE, 'w'))
        
    def render (self, frameNumber, curr = None):

        startTime = time.time()        

        command = 'blender -b ' + PROJECT_FILE + ' -o //' + OUTPUT_BLENDER_FILE + ' -F PNG -x 1 -f ' + str(frameNumber)
        os.system(command)

        endTime = time.time()
        renderTime = endTime-startTime    

        image = os.path.join(OUTPUT_DIR, self.getFileName(frameNumber))
        data = array.array('B', open(image).read()).tolist()
	startResponseTime = time.time()
        return (True, Cluster.RenderInfo(frameNumber, data, renderTime, startResponseTime))

    def getFileName (self, frameNumber):

        if frameNumber <= 9:
            return 'frame_000' + str(frameNumber) + '.png'
        elif frameNumber <= 99:
            return 'frame_00' + str(frameNumber) + '.png'
        else:
            return 'frame_0' + str(frameNumber) + '.png'
